import React, { useRef, useMemo, useState, useEffect } from 'react';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { RemindManageAPI } from '../common/type';
import { SchemaManage } from '@/components/SchemaComponent';
import { message } from 'antd';
import '../common/index.less';
import {
  closeNotifyService,
  RemindManageService,
  pauseNotifyService,
  reginNotifyService,
  deletNotifyService,
  synchroNotifyService,
  getScheduleByIDService,
} from '../services';
import {
  getRemindManageTabSwitch,
  getRemindManageTableColumns,
} from '../mconfig';
import ParticularsModal from './particularsModal';
import RemindManageAdd from './RemindManageAdd';
import StopManageView from './StopRemindModal';
import moment from 'moment';
/**引入useContext*/
import { IActionEnum, RemindPeopleContext, useUpdateReducer } from '../common';
import { getTenantID } from '@/utils';
import { loadMdicMap } from '@/services/BaseLayout';
const RemindManageView: React.FC<RemindManageAPI.IManageType> = ({
  permissions,
  curRes,
  locationProps,
}) => {
  /**上下文  reducer**/
  const prefixCls = 'schedule-update-';
  const {
    updateDispath,
    leftSelectKeys,
    leftExpandedKeys,
    leftAutoExpandParent,
    centreUserRows,
    leftSelectKeysCopy,
    leftExpandedKeysCopy,
    centreUserRowsCopy,
    deptUserList,
    deptUserListCopy,
    joinCheckBoxKeys,
    copyCheckBoxKeys,
    joinCheckBoxRows,
    copyCheckBoxRows,
    saveUserList,
    saveUserListCopy,
    userLoading,
  } = useUpdateReducer();
  /**上下文  reducer**/
  const [partid, setpartid]: any = useState();
  // state
  const [state, setState] = useState({
    ModalFlag: false, //决定弹窗的显示和隐藏
    stopFlag: false, //stop停止弹窗的显示隐藏
  });
  /**编辑的state**/
  const [editState, setEditState] = useState({
    id: '',
    flag: false,
    versionNum: 0,
    notifyStyle: 0,
  });
  /**
   * @description: 查看抽屉的显示和隐藏
   * @return {*}
   */
  const [drawer, setdrawer] = useState(false);
  const [checkRow, setCheckRow] = useState<Record<string, any>>();
  /**
   * @description: 数据字典  新增的提醒类型
   * @return {*}
   */
  const [and, setand]: any = useState();
  useEffect(() => {
    return () => {};
  });
  // 解构
  const {
    data,
    pagination,
    refreshRequest,
    loadMdicMapList,
    loading,
    searchList,
    manageTableParams,
  } = RemindManageService(permissions);
  /**
   * @description: 暂停的回调
   */
  const pauseCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };
  /**
   * @description: 结束的成功回调
   */
  const reginCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };
  /**
   * @description: 删除方法成功回调
   */
  const deletCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };
  /**
   * @description: 开启方法成功的回调
   */
  const closeCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };
  /**
   * @description: 同步方法请求成功的回调
   */
  const synchroCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };
  /**
   * @description: 暂停接口
   * @return {*}
   */
  const { pauseNotifyLoading, pauseNotifyRun } =
    pauseNotifyService(pauseCallback);
  /**
   * @description: 恢复接口
   * @return {*}
   */
  const { reginNotifyLoading, reginNotifyRun } =
    reginNotifyService(reginCallback);
  /**
   * @description: 删除接口
   * @return {*}
   */
  const { deletNotifyLoading, deletNotifyRun } =
    deletNotifyService(deletCallback);
  /**
   * @description: 开启接口
   * @return {*}
   */
  const { closeNotifyLoading, closeNotifyRun } =
    closeNotifyService(closeCallback);
  /**
   * @description: 同步接口
   * @return {*}
   */
  const { synchroNotifyLoading, synchroNotifyRun } =
    synchroNotifyService(synchroCallback);
  useEffect(() => {
    if (loadMdicMapList?.data) {
      if (`${getTenantID()}1401` !== undefined) {
        setand(loadMdicMapList?.data?.obj[`${getTenantID()}1401`]);
      }
    }
  }, [loadMdicMapList]);
  /** 头部Tab切换 */
  const onSwitch = (
    key: string | undefined | number,
    searchValues: any,
    params: any,
  ) => {
    if (key) {
      refreshRequest({ ...params, ...searchValues });
    }
  };
  /** 点击搜索重置按钮 */
  const onReset = (requestParams: any) => {
    refreshRequest(requestParams);
  };
  // 头部tab切换
  const switchList: any = useMemo(() => {
    const data = getRemindManageTabSwitch(permissions);
    return data;
  }, [permissions]);
  // 点击新增
  const getSearchOperateFuncs: any = useMemo(() => {
    return [
      {
        title: '添加',
        visible: permissions?.['/notifyController/add'] ?? false,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          setState({ ...state, ModalFlag: true });
          setEditState({ id: '', flag: false, versionNum: 0, notifyStyle: 0 });
        },
      },
    ];
  }, [permissions]);

  /**------------------------------------------------------------------------>>>
   * @description: 数据表格操作集合
   * @return {function  方法}
   */
  const getTableOperateFuncs: any = {
    /**
     * @description: 编辑方法
     */
    redactFn({ id, versionNum, notifyStyle }: any) {
      /**打开弹窗**/
      setState({ ...state, ModalFlag: true });
      /**传值**/
      setEditState({ id, flag: true, versionNum, notifyStyle });
    },
    /**
     * @description: 恢复方法
     */
    reginFn({ id, versionNum, notifyType }: any) {
      let obj = {
        id,
        versionNum,
        paramObject: {
          quartzID:
            moment(new Date()).format('YYYYMMDDHHmmss') +
            Math.floor(Math.random() * 900 + 100) +
            '',
          quartzType: notifyType,
          jobClassName: 'cn.onefox.job.QuartzDoJobs',
        },
      };
      reginNotifyRun(obj);
    },
    /**
     * @description: 暂停方法
     */
    pauseFn({ id, versionNum, notifyType }: any) {
      let obj = {
        id,
        versionNum,
        paramObject: {
          quartzID:
            moment(new Date()).format('YYYYMMDDHHmmss') +
            Math.floor(Math.random() * 900 + 100) +
            '',
          quartzType: notifyType,
          jobClassName: 'cn.onefox.job.QuartzDoJobs',
        },
      };
      pauseNotifyRun(obj);
      // deletNotifyRun(obj)
    },
    /**
     * @description: 开启方法
     */
    finishFn({
      id,
      versionNum,
      notifyType,
      executeState,
      quartzID,
      quartzType,
      jobClassName,
    }: any) {
      let obj = {
        id,
        versionNum,
        paramObject: {
          executeStyle: executeState,
          // quartzID: moment(new Date()).format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 900 + 100) + '',
          quartzID: id,
          quartzType: notifyType,
          jobClassName: 'cn.onefox.job.QuartzDoJobs',
        },
      };
      closeNotifyRun(obj);
    },
    /**
     * @description: 删除方法
     */
    deletFn({ id, notifyType }: any) {
      let obj = {
        id,
        paramObject: {
          quartzID:
            moment(new Date()).format('YYYYMMDDHHmmss') +
            Math.floor(Math.random() * 900 + 100) +
            '',
          quartzType: notifyType,
          jobClassName: 'cn.onefox.job.QuartzDoJobs',
        },
      };
      deletNotifyRun(obj);
    },
    /**
     * @description: 查看详情
     */
    getItem({ id }: any) {
      let obj = {
        id,
      };
      setpartid(obj);
      setdrawer(true);
    },
    /**
     * @description: 停止按钮
     */
    stopFn(record: Record<string, any>) {
      setCheckRow(record);
      setState({ ...state, stopFlag: true });
    },
    synchroFn(flag: boolean, record: Record<string, any>) {
      if (flag) {
        console.log('record', record);
        let obj: any = {
          id: record?.id,
          versionNum: record?.versionNum,
          isSynchro: 1,
        };
        if (record?.notifyStyle == 1) {
          obj.paramObject = {
            endTime: record?.endTime,
            startTime: record?.startTime,
            executeInterval: record?.notifyInterval,
            executeStyle: 0,
            quartzType: record?.notifyType,
            jobClassName: 'cn.onefox.job.QuartzDoJobs',
          };
        } else if (record?.notifyStyle == 2) {
          obj.paramObject = {
            executeStyle: 1,
            cronExpression: record?.cronExpression,
            quartzType: record.notifyType,
            jobClassName: 'cn.onefox.job.QuartzDoJobs',
          };
        }
        // console.log("obj====", obj)
        synchroNotifyRun(obj);
      } else {
        message.error('不可关闭');
        return;
      }
    },
  };
  // 获取数据表格数据列
  const getTableColumns: any = useMemo(() => {
    const data = getRemindManageTableColumns(
      permissions,
      getTableOperateFuncs,
      loadMdicMap,
    );
    return data;
  }, [permissions]);
  /** 点击分页操作 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    refreshRequest({ pageSize, current, ...params });
  };
  /**
   * @description: 添加按钮点击确定
   * @return {*}
   */
  const onClose = () => {
    //点击取消
    setState({ ...state, ModalFlag: false });
  };
  /**
   * @description: 搜索
   * @return {*}
   */
  const onSearch = (requestParams: any) => {
    refreshRequest(requestParams);
  };
  /**
   * 刷新管理页
   */
  const reloadManage = () => {
    refreshRequest(manageTableParams);
  };
  const getScheduleByIDCall = (res: any) => {
    if (res && res?.msgFlag) {
      if (locationProps?.state?.isCompanySchedule) {
        if (res?.obj?.joinDeptIds) {
          updateDispath({
            type: IActionEnum.LEFTSELECT_KEYS,
            payload: res?.obj?.joinDeptIds ? res?.obj?.joinDeptIds : [],
          });
          updateDispath({
            type: IActionEnum.LEFTEXPANDED_KEYS,
            payload: res?.obj?.joinDeptIds ? res?.obj?.joinDeptIds : [],
          });
        }

        if (res?.obj?.ccDeptIds) {
          updateDispath({
            type: IActionEnum.LEFTSELECT_KEYS_COPY,
            payload: res?.obj?.ccDeptIds ? res?.obj?.ccDeptIds : [],
          });
          updateDispath({
            type: IActionEnum.LEFTEXPANDED_KEYS_COPY,
            payload: res?.obj?.ccDeptIds ? res?.obj?.ccDeptIds : [],
          });
        }

        if (res?.obj?.paramObject?.joinList) {
          updateDispath({
            type: IActionEnum.CENTREUSER_ROWS,
            payload: res?.obj?.paramObject?.joinList
              ? res?.obj?.paramObject?.joinList
              : [],
          });
          updateDispath({
            type: IActionEnum.SAVE_USER_LIST,
            payload: res?.obj?.paramObject?.joinList
              ? res?.obj?.paramObject?.joinList
              : [],
          });
        }

        if (res?.obj?.paramObject?.ccList) {
          updateDispath({
            type: IActionEnum.CENTREUSER_ROWS_COPY,
            payload: res?.obj?.paramObject?.ccList
              ? res?.obj?.paramObject?.ccList
              : [],
          });
          updateDispath({
            type: IActionEnum.SAVE_USER_LIST_COPY,
            payload: res?.obj?.paramObject?.ccList
              ? res?.obj?.paramObject?.ccList
              : [],
          });
        }

        if (res?.obj?.joinIds) {
          updateDispath({
            type: IActionEnum.CENTRE_CHECKBOX_KEYS,
            payload: res?.obj?.joinIds ? res?.obj?.joinIds?.split(',') : [],
          });
        }

        if (res?.obj?.ccIds) {
          updateDispath({
            type: IActionEnum.CENTRE_CHECKBOX_KEYS_COPY,
            payload: res?.obj?.ccIds ? res?.obj?.ccIds?.split(',') : [],
          });
        }
      }
    } else {
      message.error(res?.msg);
    }
  };
  const { getScheduleByIDRun, getScheduleByIDLoading, getScheduleInfo } =
    getScheduleByIDService(getScheduleByIDCall);

  /**
   * 刷新详情
   */
  const reloadScheduleInfo = () => {
    let infoPayload = {
      ...locationProps?.state,
    };
    getScheduleByIDRun(infoPayload);
  };
  return (
    <div
      style={{
        position: 'relative',
        height: '100%',
        width: '100%',
        overflow: 'hidden',
      }}
    >
      {/* searchProps, actionList, tableProps */}
      <SchemaManage
        ref={refreshRequest}
        searchProps={{
          switchList,
          searchList,
          onSwitch,
          onReset,
          onSearch,
        }}
        actionList={getSearchOperateFuncs}
        tableProps={{
          columns: getTableColumns,
          dataSource: data?.rows,
          rowKey: 'id',
          loading:
            loading ||
            deletNotifyLoading ||
            reginNotifyLoading ||
            pauseNotifyLoading ||
            closeNotifyLoading ||
            synchroNotifyLoading,
          pagination: pagination as any,
          onPageChange: onPageChange,
        }}
      />
      {/* 新增(编辑)弹窗-------------------------- */}
      {!state.ModalFlag ? (
        ''
      ) : (
        <RemindPeopleContext.Provider
          value={{
            prefixCls,
            curRes,
            locationID: locationProps?.state?.id,
            scheduleInfo: getScheduleInfo,
            locationPageType: locationProps?.state?.isCompanySchedule,
            scheduleTimeProps: locationProps?.state?.scheduleTime,
            reloadScheduleInfo,
            scheduleInfoLoading: getScheduleByIDLoading,
            leftSelectKeys,
            leftExpandedKeys,
            leftAutoExpandParent,
            centreUserRows,
            leftSelectKeysCopy,
            leftExpandedKeysCopy,
            centreUserRowsCopy,
            deptUserList,
            deptUserListCopy,
            joinCheckBoxKeys,
            copyCheckBoxKeys,
            joinCheckBoxRows,
            copyCheckBoxRows,
            saveUserList,
            saveUserListCopy,
            userLoading,
            updateDispath,
          }}
        >
          <RemindManageAdd
            editState={editState}
            refreshRequest={reloadManage}
            arr={and}
            onClose={onClose}
          ></RemindManageAdd>
        </RemindPeopleContext.Provider>
      )}
      {/* 停止弹窗 */}
      {!state.stopFlag ? (
        ''
      ) : (
        <StopManageView
          reloadManage={reloadManage}
          checkRowObj={checkRow}
          onClose={() => {
            setState({ ...state, stopFlag: false });
          }}
        />
      )}

      <ParticularsModal
        drawer={drawer}
        onClose={() => {
          setdrawer(false);
        }}
        partid={partid}
      ></ParticularsModal>
    </div>
  );
};
export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  permissions: baseLogin?.permissions,
  navTab,
}))(RemindManageView);
